package com.relax.mybatis.encrypt.algorithm;

import com.relax.mybatis.constant.EncryptConstants;

/**
 * 
 * @author relax
 * @date 2022/07/05
 * @desc Hex加密
 */
public final class Hex {

    private static final char[] HEX = "0123456789abcdef".toCharArray();

    private Hex() {}

    public static char[] encode(byte[] data) {
        final int nBytes = data.length;
        char[] result = new char[2 * nBytes];
        int j = 0;
        for (byte aByte : data) {
            // Char for top 4 bits
            result[j++] = HEX[(0xF0 & aByte) >>> 4];
            // Bottom 4
            result[j++] = HEX[(0x0F & aByte)];
        }
        return result;
    }

    public static String encodeToString(byte[] data) {
        return new String(encode(data));
    }

    public static byte[] decode(byte[] data) {
        return decode(new String(data, EncryptConstants.DEFAULT_CHARSET));
    }

    public static byte[] decode(CharSequence data) {
        int nChars = data.length();
        if (nChars % 2 != 0) {
            throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
        }
        byte[] result = new byte[nChars / 2];
        for (int i = 0; i < nChars; i += 2) {
            int msb = Character.digit(data.charAt(i), 16);
            int lsb = Character.digit(data.charAt(i + 1), 16);
            if (msb < 0 || lsb < 0) {
                throw new IllegalArgumentException(
                    "Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");
            }
            result[i / 2] = (byte)((msb << 4) | lsb);
        }
        return result;
    }

}
